﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Linq;
using ScrumTable.BL.DM.DataManagement;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ScrumTable.DL.Data.Generic;
using ScrumTable.DL.Data.Generic.Cache;
using ScrumTable.DL.Data.Local.Test;
using ScrumTable.DL.Data.Schema.ScrumTableV1;

using WorkItemBucket = ScrumTable.DL.Data.Generic.Cache.CacheElementListEntryBucket<ScrumTable.DL.Data.Generic.Cache.CacheWorkItem>;
using WorkItemSavePair = ScrumTable.DL.Data.Generic.Cache.CacheSavePair<ScrumTable.DL.Data.Generic.Cache.CacheElementListEntryBucket<ScrumTable.DL.Data.Generic.Cache.CacheWorkItem>>;

#endregion

namespace ScrumTable.BL.DM.Test.DataManagement
{


    /// <summary>
    /// This is the test class for Attachment class.
    /// </summary>
    [TestClass]
    public class AttachmentTest : DomainBaseTest<Attachment, AttachmentSchema>
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the default instance to test.
        /// </summary>
        protected override Attachment ToTest
        {
            get { return StoryToTest.Bugs[Resources.Bug3Id].Attachments.First(); }
        }

        private UserStory StoryToTest
        {
            get { return Context.Projects[Resources.Project1Id].Stories[Resources.UserStory4Id]; }
        }

        #endregion

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new AttachmentTest instance.
        /// </summary>
        public AttachmentTest()
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Use TestInitialize to run code before running each test .
        /// </summary>
        [TestInitialize]
        public override void TestInitialize()
        {
            base.TestInitialize();
        }

        /// <summary>
        /// Use TestCleanup to run code after each test has run.
        /// </summary>
        [TestCleanup]
        public override void TestCleanup()
        {
            base.TestCleanup();
        }

        [TestMethod]
        public void TestValueChangeOnDL()
        {
            TestValueChangeWithEventOnDL(DataObjectSchema.Name, "[New Name]");
            TestValueChangeWithEventOnDL(DataObjectSchema.Uri, new Uri("http://www.example.com/"));
        }

        [TestMethod]
        public void TestValueChangeOnDM()
        {
            TestValueChangeWithEventOnDM("Name", "[New Name]");
            TestValueChangeWithEventOnDM("Uri", new Uri("http://www.example.com/"));
        }

        [TestMethod]
        public override void TestParent()
        {
            Assert.IsNotNull(ToTest.Parent);
        }

        [TestMethod]
        public void TestExtension()
        {
            Assert.IsNotNull(ToTest.Extension);
        }

        [TestMethod]
        public void TestDescription()
        {
            Assert.IsNotNull(ToTest.Description);
        }

        [TestMethod]
        public void TestUri()
        {
            Assert.IsNotNull(ToTest.Uri);
        }

        [TestMethod]
        public void TestAddAttachmentFromDataLayer()
        {
            int elementCount = StoryToTest.Attachments.Count;
            bool eventFired = false;

            DomainCollectionChangedEventHandler eventHandler =
                delegate(object sender, DomainCollectionChangedEventArgs e)
                {
                    if (e.Action == DomainCollectionChangedAction.Add)
                        eventFired = true;
                };

            // touch the story
            StoryToTest.Description = "[A New Description]";
            StoryToTest.Attachments.CollectionChanged += eventHandler;
            
            // attach new attachment to the touched story
            string newAttaUniqueId = InsertNewAttachmentFromDataDriver();

            StoryToTest.Attachments.CollectionChanged -= eventHandler;

            Assert.AreEqual(elementCount + 1, StoryToTest.Attachments.Count);
            Assert.IsTrue(eventFired);
            Assert.IsTrue(StoryToTest.Attachments.ContainsId(newAttaUniqueId));
        }

        [TestMethod]
        public void TestRemoveAttachmentFromDataLayer()
        {
            int elementCount = StoryToTest.Attachments.Count;
            bool eventFired = false;

            DomainCollectionChangedEventHandler eventHandler =
                delegate(object sender, DomainCollectionChangedEventArgs e)
                {
                    if (e.Action == DomainCollectionChangedAction.Remove)
                        eventFired = true;
                };

            // touch the story
            StoryToTest.Description = "[A New Description]";
            StoryToTest.Attachments.CollectionChanged += eventHandler;

            // remove attachment from the touched story
            string storyUniqueId = RemoveAttachmentFromDataDriver();

            StoryToTest.Attachments.CollectionChanged -= eventHandler;

            Assert.AreEqual(elementCount - 1, StoryToTest.Attachments.Count);
            Assert.IsTrue(eventFired);
            Assert.IsTrue(!StoryToTest.Attachments.ContainsId(storyUniqueId));
        }

        /// <summary>
        /// Gets the default schema of the instance to test.
        /// </summary>
        /// <param name="schema">Specifies the parent schema instance.</param>
        /// <returns>Returns the retrieved schema instance.</returns>
        protected override AttachmentSchema GetSchema(ScrumTableV1Schema schema)
        {
            return schema.AttachmentSchema;
        }

        private string InsertNewAttachmentFromDataDriver()
        {
            if (!(DataContext is GenericDataContextBase))
            {
                return null;
            }

            GenericDataContextBase dataContext = (GenericDataContextBase)DataContext;
            CacheDataChanges changes = dataContext.ExportChanges();

            // in mean time there's a new attachment on server side
            CacheAttachment newAtta = changes.Project.OwnerContext.ElementFactory.CreateAttachment(
                "Attachment 100", 100, string.Empty,
                new Uri(GetType().Assembly.Location));

            WorkItemBucket wiChange = changes.ChangedWorkItems.First().Value;
            WorkItemSavePair newSavePair = new WorkItemSavePair(wiChange)
            {
                State = CacheSavePairState.Updated
            };

            changes.WorkItemsToSync[wiChange.Element.UniqueId] = newSavePair;
            changes.WorkItemsToSync[wiChange.Element.UniqueId].Bucket.Element.Attachments.Add(newAtta);
            changes.RemoveDirtyFlags();

            // this must fire the events
            dataContext.ImportChanges(changes);
            return newAtta.UniqueId;
        }

        private string RemoveAttachmentFromDataDriver()
        {
            if (!(DataContext is GenericDataContextBase))
            {
                return null;
            }

            GenericDataContextBase dataContext = (GenericDataContextBase)DataContext;
            CacheDataChanges changes = dataContext.ExportChanges();

            WorkItemBucket wiChange = changes.ChangedWorkItems.First().Value;
            WorkItemSavePair newSavePair = new WorkItemSavePair(wiChange)
            {
                State = CacheSavePairState.Updated
            };

            changes.WorkItemsToSync[wiChange.Element.UniqueId] = newSavePair;

            // in mean time the attachment has been removed on server side
            CacheAttachment toRemove = changes.WorkItemsToSync[wiChange.Element.UniqueId].Bucket.Element.Attachments.First();
            changes.WorkItemsToSync[wiChange.Element.UniqueId].Bucket.Element.Attachments.Remove(toRemove);
            changes.RemoveDirtyFlags();

            // this must fire the events
            dataContext.ImportChanges(changes);
            return toRemove.UniqueId;
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}
